type EventCallback = (payload: any) => void;

interface EventBus {
  events: Record<string, EventCallback[]>;
  on(event: string, callback: EventCallback): void;
  off(event: string, callback: EventCallback): void;
  emit(event: string, payload?: any): void;
  once(event: string, callback: EventCallback): void;
}

/**
 * 简单的事件总线实现，用于组件间通信
 * 提供事件订阅、取消订阅、触发事件等功能
 */
const eventBus: EventBus = {
  events: {},

  /**
   * 订阅事件
   * @param event 事件名称
   * @param callback 回调函数
   */
  on(event: string, callback: EventCallback) {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].push(callback);
  },

  /**
   * 取消订阅
   * @param event 事件名称
   * @param callback 回调函数
   */
  off(event: string, callback: EventCallback) {
    if (!this.events[event]) return;
    
    this.events[event] = this.events[event].filter(cb => cb !== callback);
    
    if (this.events[event].length === 0) {
      delete this.events[event];
    }
  },

  /**
   * 触发事件
   * @param event 事件名称
   * @param payload 传递的数据
   */
  emit(event: string, payload?: any) {
    if (!this.events[event]) return;
    
    this.events[event].forEach(callback => {
      try {
        callback(payload);
      } catch (error) {
        console.error(`Error in event handler for ${event}:`, error);
      }
    });
  },
  
  /**
   * 订阅一次性事件，触发后自动取消订阅
   * @param event 事件名称
   * @param callback 回调函数
   */
  once(event: string, callback: EventCallback) {
    const onceWrapper = (payload: any) => {
      callback(payload);
      this.off(event, onceWrapper);
    };
    
    this.on(event, onceWrapper);
  }
};

export default eventBus;
